import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { Table, Pagination, MenuButton, Dialog } from '@alifd/next'
import PageHead from '../PageHead'
import * as Service from '../../service'

@withRouter
export default class Dashboard extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      data: []
    };
  }

  componentDidMount = async() => {
    this.loadList()
  }

  handleClick = () => {
    this.props.history.push('/add');
  }

  loadList = async() =>{
    this.setState({ isLoading : true })
    let data = await Service.loadList()
    this.setState({ data : data, isLoading : false })
  }

  handleWol = async(item) => {
    Dialog.confirm({
      title: '提示',
      content: '是否唤醒机器',
      onOk: async() => {
        await Service.wake(item.name)
        this.loadList()
      }
    });
  }

  handleDelete = (item) => {
    Dialog.confirm({
      title: '提示',
      content: '确认删除吗',
      onOk: async() => {
        await Service.del(item.name)
        this.loadList()
      }
    });
  };

  renderOper = (value, index, item) => {
    return (
      <MenuButton label="操作" type="primary" selectMode="single" onItemClick={key => this[key](item, this.props.history)}>
          <MenuButton.Item key={'handleWol'}>唤醒</MenuButton.Item>
          <MenuButton.Divider />
          <MenuButton.Item key={'handleDelete'}>删除</MenuButton.Item>
      </MenuButton>
    );
  };

  render() {
    const { isLoading, data } = this.state;
    return (
      <div>
        <PageHead title="机器管理" buttonText="添加" onClick={this.handleClick} />
        <Table loading={isLoading} dataSource={data} hasBorder={false}>
          <Table.Column title="名称" dataIndex="name"/>
          <Table.Column title="MAC" dataIndex="mac"/>
          <Table.Column title="操作" dataIndex="oper" cell={this.renderOper}/>
        </Table>
      </div>
    );
  }
}
